 package com.itic.mall.mobile.pay;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.utils.DateHelper;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mall.mobile.base.BaseMobileInterface;
import com.itic.mall.system.incomelog.persistence.model.IncomeLog;
import com.itic.mall.system.marketuser.persistence.model.MarketUser;
import com.itic.mall.system.marketuser.service.MarketUserService;
import com.itic.mall.system.order.persistence.model.Order;
import com.itic.mall.system.order.service.OrderService;
import com.itic.mall.system.orderpay.persistence.model.OrderPay;
import com.itic.mall.system.orderproducts.persistence.model.OrderProducts;
import com.itic.mall.system.orderproducts.persistence.model.OrderProductsExample;
import com.itic.mall.system.orderproducts.service.OrderProductsService;
import com.itic.mall.system.premoney.persistence.model.PreMoney;
import com.itic.mall.system.product.persistence.model.Product;
import com.itic.mall.system.product.service.ProductService;
import com.itic.mall.system.statis.persistence.model.Statis;
import com.itic.mall.system.statis.service.StatisService;
import com.itic.mall.system.tixian.persistence.model.Tixian;
import com.itic.mall.system.user.persistence.model.MallUser;


/**
 * 友惠家商城中心接口类
 * @author 许小宝
 * 2017年07月25日  14时11分
 */
@Controller
@RequestMapping(value="/mobile/pay")
public class MallPayInterface
     extends BaseMobileInterface {
   @Autowired
   private ProductService productService;
   @Autowired
   private OrderService orderService;
   @Autowired
   private OrderProductsService orderProductsService;
   @Autowired
   private MarketUserService marketUserService;
   @Autowired
   private StatisService statisService;
    
   
    
    /**
     * 订单项状态 ：
     * 用户生支付成功回调
     * @param request
     * @param response
     * @param token
     * @param products
     * @return
     */
    @RequestMapping(value="/wxsuccess")
    @ResponseBody
    public Map<String,Object> wxsuccess( HttpServletRequest request,HttpServletResponse response,String orderId ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//—-商品的销售数量加1(这里不做销量的统计，放在用户确认收货时统计)
			Order order = orderService.get(orderId);
			
    		//判断必要的参数
    		if( null != order && "0".equals(order.getStatus()) ){
    			String wxOrderNum = "11111";
    			
    			List<MarketUser> marketUsers = new ArrayList<MarketUser>();//是否存在商家 ID
    			List<PreMoney> preMoneys = new ArrayList<PreMoney>();//预计收益信息
    			List<OrderProducts> products = new ArrayList<OrderProducts>();
    			OrderPay orderPay = null;//支付信息
    			IncomeLog incomeLog = null;//支入信息
    			Statis statis = null;
    			
    			
    			
    			order.setPayTime(DateHelper.getDateTime());
				order.setPayType("假支付");
				order.setStatus("1");//已支付状态
				
				//将该订单下的商品项状态全部更新为支付状态 
				OrderProductsExample example = new OrderProductsExample();
				example.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andOrderIdEqualTo(orderId);
				products = orderProductsService.list(example);
				
				for( OrderProducts ttmp: products ){
					ttmp.setStatus("1");//状态为支付状态
					ttmp.setBackStatus("0");//退换货的字段
					Product product = productService.get(ttmp.getProductId());
					if(  StringHelper.isNotBlank(ttmp.getMarketUserProductId()) && StringHelper.isNotBlank(ttmp.getMarketUserId())  ){
						//商品佣金总金额 
						String totalProfit = "0";
						if( StringHelper.isNotBlank(product.getMarketProfitPercent()) && !"0".equals(product.getMarketProfit()) ){
							totalProfit = NumberStringHelper.mulString(product.getMarketProfitPercent().replace("%", ""), ttmp.getTotalMoney());
							totalProfit = NumberStringHelper.divString(totalProfit, "100", 2);
							//查找 商家 用户 添加 预计收益
							MarketUser marketUser = marketUserService.get(ttmp.getMarketUserId());
							String preProfit = "0";
							if( StringHelper.isNotBlank( marketUser.getPreProfit()) ){
								preProfit = marketUser.getPreProfit();
							}
							preProfit=NumberStringHelper.addString(preProfit, totalProfit);
							marketUser.setPreProfit(preProfit);
							
							marketUsers.add(marketUser);
							
							PreMoney preMoney = new PreMoney();//预计收益信息
							//六个必填字段
							preMoney.setId(IdGen.uuid());
							preMoney.setIsEffective(DBConst.TRUE);
							preMoney.setCreateTime(new Date());
							preMoney.setUpdateTime(new Date());
							preMoney.setCreateUser(CREATE_USER);
							preMoney.setOrgCode(ORG_CODE);
						
							//关联字段
							preMoney.setMarketUserId(marketUser.getId());
							preMoney.setProductId(product.getId());
							preMoney.setProductSkuId(ttmp.getPropertySkuId());
							preMoney.setOrderProductsId(ttmp.getId());
							//业务字段
							preMoney.setPreMoney(totalProfit);
							preMoney.setIsGive(DBConst.FALSE);
							
							preMoneys.add(preMoney);
						}
					}
				}
				
				//添加支付信息
			    orderPay = new OrderPay();
			    //六个必填字段
			    orderPay.setId(IdGen.uuid());
			    orderPay.setIsEffective(DBConst.TRUE);
			    orderPay.setCreateTime(new Date());
			    orderPay.setUpdateTime(new Date());
			    orderPay.setCreateUser(CREATE_USER);
			    orderPay.setOrgCode(ORG_CODE);
			    //关联字段
			    orderPay.setUserId(order.getUserId());
			    //业务字段
				orderPay.setPayOrderNum(order.getOrderNum());
				orderPay.setPayStatus("支付成功");
				orderPay.setPayTime( DateHelper.getDateTime());
				orderPay.setPayType("微信支付");
				orderPay.setTotalMoney(order.getTotalMoney());
    			//添加支入信息
				incomeLog = new IncomeLog();
				//六个必填字段
				incomeLog.setId(IdGen.uuid());
				incomeLog.setIsEffective(DBConst.TRUE);
				incomeLog.setCreateTime(new Date());
				incomeLog.setUpdateTime(new Date());
				incomeLog.setCreateUser(CREATE_USER);
				incomeLog.setOrgCode(ORG_CODE);
				//关联字段
				incomeLog.setUserId(order.getUserId());
				//业务字段
				incomeLog.setMoney(order.getTotalMoney());
				incomeLog.setType("微信支付");
				incomeLog.setWxOrderNum(wxOrderNum);
    			//添加平台统计信息
				statis = new Statis();
				//六个必填字段
				statis.setId(IdGen.uuid());
				statis.setIsEffective(DBConst.TRUE);
				statis.setCreateTime(new Date());
				statis.setUpdateTime(new Date());
				statis.setCreateUser(CREATE_USER);
				statis.setOrgCode(ORG_CODE);
				
				//业务字段
			    //找到当前最新的统计数据信息
				Statis tempStatis  = statisService.getLastData();
				String totalMoney = "0";
				String totalWxMoney = "0";
				if( null != tempStatis ){
					if( StringHelper.isNotBlank(tempStatis.getTotalMoney()) ){
						totalMoney = tempStatis.getTotalMoney();
					}
					
					if( StringHelper.isNotBlank(tempStatis.getTotalWxMoney()) ){
						totalWxMoney = tempStatis.getTotalWxMoney();
					}
					
				}
				totalMoney = NumberStringHelper.addString(totalMoney, order.getTotalMoney());
				statis.setTotalMoney(totalMoney);
				
				totalWxMoney = NumberStringHelper.addString(totalWxMoney, order.getTotalMoney());
				statis.setTotalWxMoney(totalWxMoney);
				
				//同步数据库更新操作
				result=orderService.paySuccess(marketUsers,preMoneys,order,products,orderPay,incomeLog,statis);
				errorCode = SUCCESS_ERROR_CODE;
	        	errorMsg = SUCCESS_ERROR_MSG;
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallPayInterface", "wxsuccess", e.toString(),"用户微信支付成功后的回调接口",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    /**
     * 用户提现到支付宝或微信成功的回调接口
     * @param request
     * @param response
     * @param token
     * @param products
     * @return
     */
    @RequestMapping(value="/tixianSuccess")
    @ResponseBody
    public Map<String,Object> tixianSuccess( HttpServletRequest request,HttpServletResponse response, String userId, String money){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(userId) && StringHelper.isNotBlank(money) && NumberStringHelper.isGreater(money, "1") ){
    			//减少用户的账户金额
    			MallUser user = mallUserService.get(userId);
    			//判断用户的金额是否大于提现金额 
    			String userMoney = "0";
				if( StringHelper.isNotBlank(user.getMoney()) ){
					userMoney = user.getMoney();
				}
				if( NumberStringHelper.isGreater(userMoney, money) ){
					//添加提现记录信息表数据
	    			Tixian tixian = new Tixian();
	    			tixian.setId(IdGen.uuid());
	    			tixian.setIsEffective(DBConst.TRUE);
	    			tixian.setCreateUser(CREATE_USER);
	    			tixian.setOrgCode(ORG_CODE);
	    			tixian.setCreateTime(new Date());
	    			tixian.setUpdateTime(new Date());
	    			
	    			tixian.setUserId(userId);
	    			tixian.setType("0");
	    			tixian.setMoney(money);
	    			tixian.setIsGive("0");
	    			
	    			
	    			
	    			userMoney = NumberStringHelper.subtractString(userMoney, money);
	    			user.setMoney(userMoney);
	    			
	    			result = mallUserService.tixianCreate( user, tixian );
	    			errorCode = SUCCESS_ERROR_CODE;
	            	errorMsg = SUCCESS_ERROR_MSG;
				}else{
					result = FAIL;
					errorCode = LESS_MONEY_ERROR_CODE;
	            	errorMsg = LESS_MONEY_ERROR_MSG;
				}
    			
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallPayInterface", "tixianSuccess", e.toString(),"用户微信提现成功后的回调接口",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
    
    /**
     * 用户退款成功的回调接口
     * @param request
     * @param response
     * @param token
     * @param products
     * @return
     */
    @RequestMapping(value="/payback")
    @ResponseBody
    public Map<String,Object> payback( HttpServletRequest request,HttpServletResponse response, String orderId ){
    	Map<String, Object> resultMap = new HashMap<String,Object>();
    	String result = FAIL;
    	String errorCode = PARAM_ERROR_CODE;
    	String errorMsg = PARAM_ERROR_MSG;
    	try{
    		//判断必要的参数
    		if( StringHelper.isNotBlank(orderId) ){
    			//根据回调的接口查找订单支付的信息
    			//更新订单状态为已成功退货
    			//更新退货信息为成功退款状态
    			//添加支出信息表数据
    			//添加平台的总统计数据
    		}
    	}catch(Exception e){
    		errorCode = SERVER_ERROR_CODE;
        	errorMsg = SERVER_ERROR_MSG;
        	//log(e);
        	logException("MallPayInterface", "payback", e.toString(),"用户微信退款成功后的回调接口",e);
    	}
    	resultMap.put(RESULT, result);
    	resultMap.put(ERROR_CODE, errorCode);
    	resultMap.put(ERROR_MSG, errorMsg);
    	isCrrossDomain(response);
    	return resultMap;
    }
    
    
}